package com.lorenzogao.pley.ui.activity


import com.jakewharton.rxbinding2.InitialValueObservable
import com.jakewharton.rxbinding2.view.RxView
import com.jakewharton.rxbinding2.widget.RxTextView
import com.lorenzogao.pley.R
import com.lorenzogao.pley.bean.LoginBean
import com.lorenzogao.pley.ui.base.BaseActivity
import com.lorenzogao.pley.ui.di.component.AppComponent
import com.lorenzogao.pley.ui.di.component.DaggerLoginComponent
import com.lorenzogao.pley.ui.di.moduel.LoginModule
import com.lorenzogao.pley.ui.presenter.LoginPresenter
import com.lorenzogao.pley.ui.presenter.contract.LoginContract
import io.reactivex.Observable
import io.reactivex.functions.BiFunction
import kotlinx.android.synthetic.main.activity_login.*


class LoginActivity : BaseActivity<LoginPresenter>(), LoginContract.LoginView {


    override fun checkPhoneSuccess() {
        til_login_moblie.error = ""
        til_login_moblie.isErrorEnabled = false
    }


    override fun showLodading() {

    }

    override fun showError(msg: String) {

    }

    override fun dimissLoading() {

    }

    override fun checkPhoneError() {
        til_login_moblie.error = "手机号码输入错误"
    }

    override fun LoginSuccess(loginBean: LoginBean) {
        this.finish()
    }

    override fun LoginError(msg: String) {

    }


    override fun setupActivityComponent(appComponent: AppComponent) {
        DaggerLoginComponent.builder().appComponent(appComponent).loginModule(LoginModule(this)).build().inject(this)
    }

    override fun setLayout(): Int {
        return R.layout.activity_login
    }

    override fun initData() {

    }


    override fun initView() {


        var moblie: InitialValueObservable<CharSequence> = RxTextView.textChanges(ed_login_moblie)
        var password: InitialValueObservable<CharSequence> = RxTextView.textChanges(ed_login_password)

        Observable.combineLatest(moblie, password, BiFunction<CharSequence, CharSequence, Boolean>
        { t, u -> isPhoneValid(t.toString()) && isPassWordValid(u.toString()) }).subscribe({ aBoolean ->
            RxView.enabled(btn_login).accept(aBoolean)
        })



        RxView.clicks(btn_login).subscribe({
            mPresenter.login(ed_login_moblie.text.toString().trim(), ed_login_password.text.toString().trim())
        })




    }


    private fun isPhoneValid(phone: String): Boolean {
        return phone.length == 11
    }

    private fun isPassWordValid(password: String): Boolean {
        return password.length >= 6
    }


}
